package com.yixuan.mt.console.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yixuan.mt.common.response.Result;
import com.yixuan.mt.common.utitls.AdminTokenUtils;
import com.yixuan.mt.common.utitls.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 登录操作直接放行
        if (request.getServletPath().equals("/op/login") || request.getMethod().equals("OPTIONS")) {
            return true;
        }
        // 校验token
        try {
            String authorization = request.getHeader("Authorization");
            if (authorization == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(Result.error("未登录！")));
                return false;
            }
            String token = authorization.substring(7);
            Claims claims = AdminTokenUtils.parseJwt(token);
            UserContext.setUser((Integer) claims.get("id"));

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(Result.error("未登录！")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
